package cn.zhuzicc.reflect;

import java.lang.annotation.*;
import java.lang.reflect.Field;

/**
 * @author zx
 * @version 1.0
 * @className: Test12
 * @description: 反射操作注解
 * @date: 2021/4/28 15:46
 */
public class Test12 {
    public static void main(String[] args) throws ClassNotFoundException {
        Class c1 = Class.forName("cn.zhuzicc.reflect.Person1");

        // 1. 通过反射获取注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println("1. 通过反射获取注解:\n" + annotation);
        }

        // 2. 获取注解中的属性值
        TableName annotation = (TableName) c1.getAnnotation(TableName.class);
        String value = annotation.value();
        System.out.println("2. 获取注解中的属性值:\n" + value);

        // 3. 获取字段注解
        Field[] declaredFields = c1.getDeclaredFields();
        System.out.println("3. 获取字段注解:");
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            ColunmName colunmName = declaredField.getAnnotation(ColunmName.class);
            System.out.print(colunmName.name() + ",");
            System.out.print(colunmName.length() + ",");
            System.out.print(colunmName.type());
            System.out.println("\n");
        }
    }
}


@TableName("person_info")
class Person1 {
    @ColunmName(name = "db_name", type = "varchar", length = 5)
    private String name;

    @ColunmName(name = "db_age", type = "int", length = 3)
    private int age;

    @ColunmName(name = "db_stature", type = "int", length = 3)
    private int stature;

    @ColunmName(name = "db_weight", type = "int", length = 3)
    private int weight;

    public Person1() {
    }

    public Person1(String name, int age, int stature, int weight) {
        this.name = name;
        this.age = age;
        this.stature = stature;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getStature() {
        return stature;
    }

    public void setStature(int stature) {
        this.stature = stature;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Person1{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", stature=" + stature +
                ", weight=" + weight +
                '}';
    }
}

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface TableName {
    String value();
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface ColunmName {
    String name();

    String type();

    int length();
}